View Modifiers are structures which allow you to apply the same style to multiple Views or other Modifiers.
Apply Modifier to View
struct ContentView: View {
struct LabelStyle : ViewModifier {
func body(content: Content) -> some View {
return content
.foregroundColor(Color.red)
.shadow(color: Color.black, radius: 2, x: 2, y: 2)
.font(Font.custom("Arial Rounded MT Bold", size: 18))
}
}
var body: some View {
Text("Score").modifier(LabelStyle())
}
}
Apply Modifier to Modifier
struct ContentView: View {
struct ShadowStyle : ViewModifier {
func body(content: Content) -> some View {
return content
.shadow(color: Color.black, radius: 2, x: 2, y: 2)
}
}
struct LabelStyle: ViewModifier {
func body(content: Content) -> some View {
return content
.modifier(ShadowStyle())
.foregroundColor(Color.red)
.font(Font.custom("Arial Rounded MT Bold", size: 18))
}
}
struct ValueStyle: ViewModifier {
func body(content: Content) -> some View {
return content
.modifier(ShadowStyle())
.foregroundColor(Color.black)
.font(Font.custom("Arial Rounded MT Bold", size: 24))
}
}
var body: some View {
HStack {
Text("Score:").modifier(LabelStyle())
Text(String("10")).modifier(ValueStyle())
}
}
}